package com.foreknow.controller;

import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.GuestBook;
import com.foreknow.service.GuestBookService;
import com.foreknow.service.impl.GuestBookServiceImpl;
import com.foreknow.util.Pagination;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ManagerServlet extends HttpServlet {
    private int pageSize = 10;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数q
        String method = req.getParameter("q");
        if ("delete".equals(method)) {
            delete(req, resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        } else {
            list(req, resp);
        }
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //获取初始化参数pageSize
        this.pageSize = Integer.parseInt(config.getServletContext().getInitParameter("pageSize"));
    }

    //查询所有留言信息
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();
        int pageNumber = 0;
        //获取请求参数(pageNo页码)
        try {
            //当第一次进入到list.jsp的时候，页码是获取不到的，如果获取不到页码就执行catch，将pageNumber置为1
            pageNumber = Integer.parseInt(req.getParameter("pageNo"));
        }catch (Exception e){
            pageNumber = 1;
        }
        //调用Service中的方法获取数据并显示
        GuestBookService service = new GuestBookServiceImpl();
        Pagination pagination = service.getByPage(pageSize, pageNumber);
        EntityMapping mapping = MappingFactory.getInstance().getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = pagination.getList(mapping);
        //要将list集合在服务器端保存（后端就可以在页面中获取到list集合)
        //req.setAttribute("list", list);
        session.setAttribute("list",list);
        session.setAttribute("total",pagination.getMaxElements());
        //将资源转发到list.jsp
        req.getRequestDispatcher("/list.jsp").forward(req, resp);
        //重定向
        //resp.sendRedirect(req.getContextPath() + "/list.jsp");
    }

    //根据id删除留言信息
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        GuestBookService service = new GuestBookServiceImpl();
        boolean isRight = service.gDelete(Integer.parseInt(req.getParameter("id")));
        if (isRight) {
//            list(req,resp);
            //重定向
            resp.sendRedirect(req.getContextPath() + "/ManagerServlet");
        } else {
            out.println("删除失败");
        }
    }

    //根据id修改留言信息
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端发送请求的字符编码集
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        GuestBookService service = new GuestBookServiceImpl();
        GuestBook gb = service.gQueryById(id);

        gb.setName(gb.getName());
        gb.setPhone(gb.getPhone());
        gb.setEmail(gb.getEmail());
        gb.setTitle(gb.getTitle());
        gb.setContent(gb.getContent());
        req.setAttribute("gb", gb);
        req.getRequestDispatcher("Update.jsp").forward(req, resp);

        resp.sendRedirect(req.getContextPath() + "/Update.jsp");
    }

    protected void updateSubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        GuestBookService service = new GuestBookServiceImpl();
//        GuestBook gb = new GuestBook();
//        gb.setId(Integer.parseInt(req.getParameter("id")));
//        int id = gb.getId();
//        gb.setName(req.getParameter("name"));
//        gb.setPhone(req.getParameter("phone"));
//        gb.setEmail(req.getParameter("email"));
//        gb.setTitle(req.getParameter("title"));
//        gb.setContent(req.getParameter("content"));
////        List<GuestBook> list = new ArrayList<>();
////        list.add(gb);
//        service.gUpdate(gb, id);
////        //重定向
////        resp.sendRedirect(req.getContextPath()+"/ManagerServlet");
//
//        //显示所有留言信息（转发）
//        req.getRequestDispatcher("/ManagerServlet?q=list").forward(req,resp);
    }
}
